<template>
  <!-- 投放模式的数据概览-->
  <div style="margin-bottom: 48px">
    <!-- 数据概览卡片开始 -->
    <div
      v-loading="targetLoading"
      class="data"
      element-loading-text="数据加载中,请稍候"
    >
      <chartBox
        :echart-info="echartInfo.result"
        :card-data="echartInfo"
        :start-time="queryEchart.startTime"
        :end-time="queryEchart.endTime"
      >
        <num-card
          title="总花费"
          :list="echartInfo.result"
          :time-arr="[queryEchart.startTime, queryEchart.endTime]"
          :current-period="echartInfo.now.localSpendAmountDouble || 0"
          :previous-period="echartInfo.old.localSpendAmountDouble * 1 || 0"
          :bfore-yesterday-num="
            echartInfo.dayBeforeYesterday.localSpendAmountDouble * 1
          "
          :yesterday-num="echartInfo.yesterday.localSpendAmountDouble * 1"
        />
      </chartBox>
    </div>
    <!-- 数据概览结束 -->
    <!-- 趋势对比开始 -->
    <el-card
      v-loading="echartLoading"
      class="trend-card"
      element-loading-text="数据加载中,请稍候"
      shadow="never"
    >
      <div class="trend">
        <cell-header title="趋势对比" />
        <div>
          <date-echart :date-info="echartList">
            <div slot="right">
              <el-radio-group
                v-model="queryEchart.type"
                size="small"
                @change="quShiChartData"
              >
                <el-radio-button label="DAILY">每天</el-radio-button>
                <el-radio-button
                  label="HOURLY"
                  :disabled="
                    $getDiffDay(queryEchart.endTime, queryEchart.startTime) > 31
                  "
                  >每小时</el-radio-button
                >
              </el-radio-group>
            </div>
          </date-echart>
        </div>
      </div>
    </el-card>

    <!-- 趋势对比结束 -->

    <!-- 广告系列表格展示开始 -->
    <table-box></table-box>
    <!-- 广告系列表格展示结束-->
  </div>
</template>

<script>
import dateEchart from "@/components/charts/dateEchart.vue";
import cellHeader from "@/components/cell-header.vue";
import chartsCard from "../components/charts-card.vue";
import numCard from "../components/num-card.vue";
import tableBox from "./components/tableBox.vue";
import chartBox from "./components/chart-box/index.vue";
import { isBindWeixin } from "@/api/user.js";

import { echartsOptions } from "@/settings.js";
import { findReportCampaignTotal } from "@/api/overView.js";

export default {
  components: {
    chartsCard,
    numCard,
    dateEchart,
    cellHeader,
    tableBox,
    chartBox,
  },

  data() {
    return {
      number: 0,
      timer: undefined,
      time: "",
      /* 核心指标*/
      targetLoading: false,
      echartInfo: {
        now: {},
        old: {},
        dayBeforeYesterday: {},
        yesterday: {},
      }, // 具体信息

      //* 图表接口 */
      echartLoading: false,
      queryEchart: {
        audienceType: "countryOrRegion",
        typeValue: "",
        campaignId: "", // 如果不是单个campaign就不填
        country: "",
        countrySX: this.$store.state.user.timeZone, // 时区
        timeZone: this.$store.getters.timeZoneTime, // 时区比UTC时间少几个小时
        startTime: this.$store.state.overview.timeObj.overViewTime.startTime, // 开始时间
        endTime: this.$store.state.overview.timeObj.overViewTime.endTime, // 结束时间
        name: "", // 查询时的名称  模糊查询
        status: "", // 状态
        userId: this.$store.state.user.userInfo.userId,
        adChannelType: "", // 投放位置
        orgId: this.$route.query.orgId || "", // 如果是自助投放为空
        uuid: this.$route.query.uuid || "",
        aId: this.$route.query.aId || this.$route.query.aid || "",
        currencyType: this.$store.state.user.unit,
        type: "DAILY", // 每天：'DAILY' 每小时'HOURLY'
        teamId: this.$store.state.team.teamId || "", // 团队
        campaignGroupId: this.$route.query.serialId || "",
      },
      echartsOptions, // ehcarts图表的显示类型按钮组
      echartList: [], // 要显示的图表数据
      detailShow: true,
    };
  },
  computed: {
    // 选择的时区
    timeZone() {
      return this.$store.state.user.timeZone;
    },

    // 选择的结算币种
    unitTxt() {
      const unit = this.$store.state.user.unit;
      this.$forceUpdate();
      return unit === "RMB" ? "￥" : "$";
    },
    // 选择的开始时间与结束时间
    timeObj() {
      console.log(this.$store.state.overview.timeObj.overViewTime);
      return this.$store.state.overview.timeObj.overViewTime;
    },

    // 选择的图表显示项目
    echartXData() {
      if (this.echartList.length) {
        const arr = this.echartList.map((item) => {
          return item.date;
        });
        return arr;
      } else {
        return [];
      }
    },
  },

  watch: {
    timeZone: {
      deep: true,
      handler: function (newV, oldV) {
        this.queryEchart.countrySX = this.$store.state.user.timeZone; // 时区
        this.queryEchart.timeZone = this.$store.getters.timeZoneTime;
        if (this.$route.query.uuid) {
          this.getTargetChartData(); // 核心指标查询图表数据
          this.quShiChartData();
        }
      },
    },
    timeObj: {
      // �����Ķ���
      deep: true,
      handler: function (newV, oldV) {
        if (this.$route.query.uuid) {
          this.pieckerChange(newV);
        }
      },
    },

    $route: {
      deep: true,
      handler: function (newV, oldV) {
        if (this.timer) {
          clearTimeout(this.timer);
        }
        if (this.$route.query.uuid) {
          this.timer = setTimeout(() => {
            this.$nextTick(() => {
              if (this.$route.query.uuid) {
                this.getTargetChartData(); // 核心指标查询图表数据
                this.quShiChartData();
              }
            });
          }, 1000);
        }
      },
    },
  },

  created() {},
  mounted() {
    this.number = 0;
    if (localStorage.getItem("character")) {
      this.isBindWeixin();
    }
    if (this.$route.query.uuid) {
      this.pieckerChange(this.$store.state.overview.timeObj.overViewTime);
    }
  },
  methods: {
    async isBindWeixin() {
      let data = {
        wechatLoginUuid: localStorage.getItem("character"),
      };
      let res = await isBindWeixin(data);
      if (res.data.code === 20000) {
        this.$message.closeAll();
        localStorage.setItem("character", "");
        if (res.data.data.type === 4)
          return this.$message.error(res.data.message);
        if (res.data.data.type === 3)
          return this.$message.success(res.data.message || "微信绑定成功");
        window.localStorage.setItem("character", "");
      } else {
        if (this.number === 4) {
          window.localStorage.setItem("character", "");
        } else {
          this.number++;
          setTimeout(() => {
            this.isBindWeixin();
          }, 2000);
        }
      }
    },
    // 时间发生了变化；
    pieckerChange(data) {
      this.queryEchart.startTime = data.startTime;
      this.queryEchart.endTime = data.endTime;
      if (
        this.$getDiffDay(this.queryEchart.endTime, this.queryEchart.startTime) >
        31
      ) {
        this.queryEchart.type = "DAILY";
      }
      this.$nextTick(() => {
        this.getTargetChartData(); // 核心指标查询图表数据
        this.quShiChartData();
      });
    },

    // 核心指标查询图表数据   只需要获取每天的数据变化
    async getTargetChartData() {
      /* alert(this.$route.query.aId) */
      this.targetLoading = true;
      const obj = {
        ...this.queryEchart,
        teamId: this.$store.state.team.teamId || "",
        campaignGroupId: this.$route.query.serialId || "",
        type: "DAILY", // 每天：'DAILY' 每小时'HOURLY'
        orgId: this.$route.query.orgId || "", // 如果是自助投放为空
        uuid: this.$route.query.uuid || "",
        aId: this.$route.query.aId || this.$route.query.aid || "",
      };
      const res = await findReportCampaignTotal(obj);
      this.targetLoading = false;
      if (res.data.code === 20000) {
        this.echartInfo = JSON.parse(JSON.stringify({ ...res.data.data }));
      } else {
        this.$message.closeAll();
        this.$message.error(
          res.data.message || "趋势对比图表数据获取失败，请稍后重试"
        );
      }
    },

    // 趋势对比查询图表数据   这里可以获取每小时的数据变化
    async quShiChartData() {
      this.echartLoading = true;
      const obj = {
        ...this.queryEchart,
        teamId: this.$store.state.team.teamId || "",
        campaignGroupId: this.$route.query.serialId || "",
        orgId: this.$route.query.orgId || "", // 如果是自助投放为空
        uuid: this.$route.query.uuid || "",
        aId: this.$route.query.aId || this.$route.query.aid || "",
      };

      const res = await findReportCampaignTotal(obj);
      this.echartLoading = false;
      if (res.data.code === 20000) {
        this.echartList = JSON.parse(JSON.stringify(res.data.data.result));
      } else {
        this.$message.closeAll();
        this.$message.error(
          res.data.message || "趋势对比图表数据获取失败，请稍后重试"
        );
      }
    },

    /* 这里是图表变化*/
    // 查询广告系列组  图表变化
  },
};
</script>

<style lang="scss" scoped="true">
.trend-card {
  margin-bottom: 24px;
}

.table-box {
  .series-table {
    margin-top: 24px;
  }
}

@import "../components/handle.scss";
</style>
